/*
 * util_string.c
 *
 *  Created on: Mar 23, 2012
 *      Author: lin
 */

#include <assert.h>
#include <string.h>

#include "zmalloc/zmalloc.h"
#include "collection/link_list.h"

#include "util_string.h"

char** string_sub(const char *str, const char *delim, int *num) {
    assert(str && num);
    char *s = zstrdup(str);
    int arraynum;
    char ** array = string_split(s, delim, &arraynum);

    if (arraynum == 0) {
        return NULL;
    }
    char ** subs = zmalloc(sizeof(char*) * arraynum);
    int delimlen = strlen(delim);
    char *prevsub = NULL;
    int prevlen = 1;
    for (int i = 0; i < arraynum; i++) {
        prevlen += strlen(array[i]);
        if (i != 0) {
            prevlen += delimlen;
        }
        char *sub = zcalloc(prevlen);
        if (prevsub) {
            strcat(sub, prevsub);
            strcat(sub, delim);
        }
        strcat(sub, array[i]);
        subs[i] = sub;
        prevsub = sub;
    }
    *num = arraynum;
    return subs;
}

char** string_split(char *str, const char *delim, int *num) {
    assert(str && delim && num);
    char *saveptr = NULL;

    char *token = strtok_r(str, delim, &saveptr);
    if (token == NULL) {
        *num = 0;
        return NULL;
    }

    link_list_t list;
    l_list_reset(&list);

    while (token != NULL) {
        l_list_add_tail(&list, token);
        token = strtok_r(NULL, delim, &saveptr);
    }
    *num = l_list_len(&list);
    char ** array = (char **) l_list_to_array(&list);
    l_list_clear(&list);
    return array;
}

